package com.huatai.datacenter.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.api.R;
import com.huatai.common.httputil.HttpRequest;
import com.huatai.datacenter.entity.TopicInfoEntity;
import com.huatai.datacenter.entity.datamodel.DataModelFieldEntity;
import com.huatai.datacenter.entity.postdata.HttpRequestEntity;
import com.huatai.datacenter.mapper.HttpRequestMapper;
import com.huatai.datacenter.mapper.TopicInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lion
 * @date 2023/6/14  18:33
 */
@Service
public class HttpRequestService extends BaseService<HttpRequestMapper, HttpRequestEntity> {

	@Autowired
	private DataModelApplyService dataModelApplyService;

	@Autowired
	private QualityLogService qualityLogService;

	/**
	 * xxl-job的接口地址
	 */
	private static final String jobAdminAddress = "http://127.0.0.1:6610/xxl-job-admin/request/";

	/**
	 * @author Lion
	 * @description 添加任务
	 * @param data
	 * @return java.lang.String
	 */
	public String saveRequestData(HttpRequestEntity data){

		//保存数据到job任务中
		JSONObject jobInfoEntity = new JSONObject();
		jobInfoEntity.put("jobGroup", 2);
		jobInfoEntity.put("jobDesc", data.getJoinName());
		jobInfoEntity.put("author", "Lion");
		jobInfoEntity.put("scheduleType", "CRON");
		jobInfoEntity.put("scheduleConf", data.getCron());
		jobInfoEntity.put("misfireStrategy", "DO_NOTHING");
		jobInfoEntity.put("executorRouteStrategy", "FIRST");
		jobInfoEntity.put("executorHandler", "httpJobHandler");
		jobInfoEntity.put("executorBlockStrategy", "SERIAL_EXECUTION");
		jobInfoEntity.put("executorTimeout", 0);
		jobInfoEntity.put("executorFailRetryCount", 0);
		jobInfoEntity.put("glueType", "BEAN");
		jobInfoEntity.put("glueRemark", "GLUE代码初始化");
		jobInfoEntity.put("triggerStatus", 0);

		//封装调度任务数据
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("url",data.getApiAddress());
		jsonParam.put("method",data.getRequestType());
		jsonParam.put("data",data.getBodyData());
		jsonParam.put("id",data.getJobId());
		jobInfoEntity.put("executorParam", jsonParam.toJSONString());

		jobInfoEntity.put("jobId",data.getJobId());

		String resultData = HttpRequest
			.post(jobAdminAddress  + "addData")
			.bodyString(jobInfoEntity.toString())
			.execute().asString();

		data.setStatus(0);
		data.setJobId(Integer.valueOf(resultData));
		save(data);
		//新增模型应用记录
		saveRequestModel(data);

		return "success";
	}

	public String updateRequestData(HttpRequestEntity data){

		//保存数据到job任务中
		JSONObject jobInfoEntity = new JSONObject();
		jobInfoEntity.put("jobGroup", 2);
		jobInfoEntity.put("jobDesc", data.getJoinName());
		jobInfoEntity.put("author", "Lion");
		jobInfoEntity.put("scheduleType", "CRON");
		jobInfoEntity.put("scheduleConf", data.getCron());
		jobInfoEntity.put("misfireStrategy", "DO_NOTHING");
		jobInfoEntity.put("executorRouteStrategy", "FIRST");
		jobInfoEntity.put("executorHandler", "httpJobHandler");
		jobInfoEntity.put("executorBlockStrategy", "SERIAL_EXECUTION");
		jobInfoEntity.put("executorTimeout", 0);
		jobInfoEntity.put("executorFailRetryCount", 0);
		jobInfoEntity.put("glueType", "BEAN");
		jobInfoEntity.put("glueRemark", "GLUE代码初始化");
		jobInfoEntity.put("triggerStatus", 0);
		jobInfoEntity.put("id",data.getJobId());

		//封装调度任务数据
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("url",data.getApiAddress());
		jsonParam.put("method",data.getRequestType());
		jsonParam.put("data",data.getBodyData());
		jsonParam.put("id",data.getJobId());
		jobInfoEntity.put("executorParam", jsonParam.toJSONString());

		jobInfoEntity.put("jobId",data.getJobId());

		HttpRequest
			.post(jobAdminAddress  + "updateData")
			.bodyString(jobInfoEntity.toJSONString())
			.execute().asString();
		updateById(data);

		return "success";
	}

	/**
	 * @author Lion
	 * @description 启动任务
	 * @param data
	 * @return java.lang.String
	 */
	public String startJob(@RequestBody JSONObject data) {

		int jobId = data.getInteger("jobId");
		String resultData = HttpRequest
			.post(jobAdminAddress  + "start")
			.bodyString(String.valueOf(jobId))
			.execute().asString();

		//更新状态
		updateStatus(jobId,1);

		return resultData;
	}

	/**
	 * @author Lion
	 * @description 停止job
	 * @param data
	 * @return java.lang.String
	 */
	public String stopJob(@RequestBody JSONObject data) {

		int jobId = data.getInteger("jobId");
		String resultData = HttpRequest
			.post(jobAdminAddress  + "stop")
			.bodyString(String.valueOf(jobId))
			.execute().asString();
		//更新状态
		updateStatus(jobId,0);

		return resultData;
	}

	/**
	 * @author Lion
	 * @description 删除调度任务
	 * @param data
	 * @return java.lang.String
	 */
	public String removeData(List<String> data){
		String resultData = "";
		for (int i=0;i<data.size();i++){

			resultData = HttpRequest
				.post(jobAdminAddress  +"remove")
				.bodyString(data.get(i))
				.execute().asString();
		}
		return resultData;
	}

	/**
	 * @author Lion
	 * @description 执行一次
	 * @param jobId
	 * @return java.lang.String
	 */
	public String triggerJob(String jobId){
		String resultData = HttpRequest
			.post(jobAdminAddress  +"trigger")
			.bodyString(jobId)
			.execute().asString();
		return resultData;
	}

	public String pageTaskJob(JSONObject json){
		String resultData = HttpRequest
			.post(jobAdminAddress  +"pageList")
			.bodyJson(json)
			.execute().asString();
		return resultData;
	}


	/**
	 * @author Lion
	 * @description 更新状态
	 * @param  jobId
	 * @return void
	 */
	public void updateStatus(int jobId,int status){

		QueryWrapper<HttpRequestEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("jobId",jobId);
		HttpRequestEntity httpRequestEntity = this.getOne(queryWrapper);
		httpRequestEntity.setStatus(status);
		this.updateById(httpRequestEntity);
	}

	/**
	 * @author Lion
	 * @description 如果选择模型id，则在模型应用中新增该条记录
	 * @param data
	 * @return void
	 */
	public void saveRequestModel(HttpRequestEntity data){
		if (data.getModelId() != null){
			dataModelApplyService.saveDataModelApplyInstance(data.getModelId(),data.getModelName(),data.getId(),data.getJoinName(),"接入类数据模型");
		}
	}

	/**
	 * @author Lion
	 * @description 获取请求调度任务日志
	 * @param
	 * @return java.lang.String
	 */
	public String queryData(){

		List<Integer> list = super.list().stream().map(HttpRequestEntity::getJobId).collect(Collectors.toList());

		String resultData = HttpRequest
			.post(jobAdminAddress  +"logData")
			.bodyJson(list)
			.execute().asString();

		return resultData;
	}
}
